const Koa = require("koa");
const koaRouter = require("koa-router");

const server = new Koa();
const router = new koaRouter();

server.keys = ["kkb"];
router.get("/user", async (ctx, next) => {
    let user = null;

    try {
        user = ctx.cookies.get("user", {
            signed: true,
        });
        console.log(user);
    } catch (e) {
        ctx.throw(401, "没有权限");
    }

    if (!user) {
        ctx.throw(401, "没有权限");
    } else {
        ctx.body = "大海和小蕊";
    }
});

router.post("/login", async (ctx, next) => {
    let user = {
        id: 1,
        username: "zmouse",
    };

    ctx.cookies.set("user", JSON.stringify(user), { signed: true });

    // 设置多个cookie
    // ctx.cookies.set("A",1)
    // ctx.cookies.set("B",2)
    ctx.body = "授权成功";
});

server.use(router.routes());

server.listen("8080");
